package org.dftproject.genesis.core.agents.scheduler;

import java.util.ArrayList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dftproject.genesis.core.agents.AgentManager;
import org.dftproject.genesis.core.agents.IAgent;
import org.dftproject.genesis.core.agents.IAgentManagerListener;

public class AgentScheduler {

	private static final Log log = LogFactory.getLog(AgentScheduler.class);
	
	private static final int numThreads = 1;
	
	private ArrayList<IAgent> agents;
	private int nextAgent = 0;
	
	private IAgentManagerListener agentManagerListener;

	public void start() {
		agents = new ArrayList<IAgent>(AgentManager.getDefault().getAgents());
		
		agentManagerListener = new IAgentManagerListener() {

			public void agentAdded(IAgent agent) {
				agents.add(agent);
			}

			public void agentRemoved(IAgent agent) {
				agents.remove(agent);
			}

			public void agentUpdated(IAgent agent) {
			}
			
		};
		AgentManager.getDefault().addListener(agentManagerListener);
		
		for (int i = 0; i < numThreads; i++) {
			AgentSchedulerJob job = new AgentSchedulerJob(this);
			job.schedule();
		}
		
		log.info("Agent scheduler started");
	}

	public void stop() {
		AgentManager.getDefault().removeListener(agentManagerListener);
		
		log.info("Agent scheduler stopped");
	}

	public Runnable getWork() {
		if (agents.isEmpty())
			return null;
		if (nextAgent > agents.size() - 1)
			nextAgent = 0;
		
		Runnable work = null;
		
		int firstAgent = nextAgent;
		do {
			work = agents.get(nextAgent).getNextTask();
			nextAgent = (nextAgent + 1) % agents.size();
		} while (work == null && nextAgent != firstAgent);
		
		return work;
	}

}
